package com.elink.enginerring.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elink.enginerring.co.BaseCo;
import com.elink.enginerring.co.PostbarCo;
import com.elink.enginerring.common.CoinEnum;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.common.HessianResultEnum;
import com.elink.enginerring.common.HessionEnum;
import com.elink.enginerring.common.Pagination;
import com.elink.enginerring.dao.LabelMapper;
import com.elink.enginerring.dao.PostbarDcMapper;
import com.elink.enginerring.dao.PostbarMapper;
import com.elink.enginerring.dao.ReplyMapper;
import com.elink.enginerring.dao.SecondaryCategoryMapper;
import com.elink.enginerring.dao.TopCategoryMapper;
import com.elink.enginerring.domain.Label;
import com.elink.enginerring.domain.Postbar;
import com.elink.enginerring.domain.PostbarDc;
import com.elink.enginerring.domain.SecondaryCategory;
import com.elink.enginerring.domain.TopCategory;
import com.elink.enginerring.hessian.CoinHessianService;
import com.elink.enginerring.hessian.PersonDynamicHessianService;
import com.elink.enginerring.service.PostbarService;
import com.elink.enginerring.util.JSONUtil;
import com.elink.enginerring.util.UUIDUtil;
import com.elink.enginerring.vo.CategoryListOfHier;
import com.elink.enginerring.vo.CategoryListOfInternal;
import com.elink.enginerring.vo.HessianMessage;
import com.elink.enginerring.vo.PostbarVo;

@Service("postBarService")
public class PostbarServiceImpl implements PostbarService {
	@Autowired
	private PostbarMapper postbarMapper;
	@Autowired
	private ReplyMapper replyMapper;
	@Autowired
	private PostbarDcMapper postbarDcMapper;
	@Autowired
	private TopCategoryMapper topCategoryMapper;
	@Autowired
	private SecondaryCategoryMapper secondaryCategoryMapper;
	@Autowired
	private PersonDynamicHessianService  personDynamicHessianService;
	@Autowired
	private CoinHessianService coinHessianService;
	@Autowired
	private LabelMapper labelMapper;

	@Override
	public Map<String, Object> getList(PostbarCo co) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", postbarMapper.selectList(co));
		map.put("Pagination", new Pagination(co, postbarMapper.selectCount(co)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getInfo(String pbId,BaseCo co,String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		PostbarVo pv = postbarMapper.getInfo(pbId,userId);
		map.put("info", pv);
		map.put("list", replyMapper.getReplyByPrimaryKey(pbId,co,userId));
		map.put("Pagination", new Pagination(co, replyMapper.selectCount(pbId)));
		
		//更新浏览量
		pv.setBrowseCount(pv.getBrowseCount()+1);
		postbarMapper.updateByPrimaryKeySelective(pv);
		
		//头部路径
		TopCategory top = topCategoryMapper.selectByPrimaryKey(pv.getTcId());
		SecondaryCategory sec = secondaryCategoryMapper.selectByPrimaryKey(pv.getScId());
		
		map.put("top", top);
		map.put("sec", sec);
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> add(Postbar postbar,String dcIds) {
		if(postbar.getPrice() != 0){
			//扣除积分
			HessianMessage message = coinHessianService.modifyCoin(postbar.getPostbarId(), CoinEnum.ADDPOST.getIndex(),postbar.getPrice().intValue(), postbar.getUserId(), null);
			if(message.getCode() ==HessianResultEnum.CoinNotEnough.getIndex()){//余额不足
				return JSONUtil.getJSON(ErrorType.SUCCESS,message.getMsg());
			}
		}
		String postbarId = UUIDUtil.getUUID();
		postbar.setPostbarId(postbarId);
		postbar.setTime(new Date());
		
		List<PostbarDc> fdc = new ArrayList<PostbarDc>();
		if(dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				PostbarDc pbd = new PostbarDc();
				pbd.setPostBarId(postbarId);
				pbd.setDcId(Integer.parseInt(dcId));
				fdc.add(pbd);
			}
			postbarDcMapper.insertBatch(fdc);
		}
		postbarMapper.insertSelective(postbar);
		//远程备份
		try {
			personDynamicHessianService.addPersonDynamic(HessionEnum.ADDQUESTION.getIndex(),0,postbar.getTitle(),postbar.getContent(),
					postbar.getUserId(),postbarId,null);
		} catch (Exception e) {
			  Logger logger = Logger.getLogger(PostbarServiceImpl.class);
			  logger.info("远程提交问题失败"+e);
		}
		
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> modify(Postbar postbar,String dcIds,String oldDcId) {
//		if(postbar.getPrice() != 0){
//			//扣除积分
//			HessianMessage message = coinHessianService.modifyCoin(postbar.getPostbarId(), CoinEnum.ADDPOST.getIndex(),
//					postbar.getPrice().intValue(), postbar.getUserId(), null);
//			if(message.getCode() ==HessianResultEnum.CoinNotEnough.getIndex()){//余额不足
//				return JSONUtil.getJSON(ErrorType.SUCCESS,message.getMsg());
//			}
//		}
		
		//删掉旧的分类
		postbarDcMapper.delByPostbarId(postbar.getPostbarId());
		
		List<PostbarDc> fdc = new ArrayList<PostbarDc>();
		if(dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				PostbarDc pbd = new PostbarDc();
				pbd.setPostBarId(postbar.getPostbarId());
				pbd.setDcId(Integer.parseInt(dcId));
				fdc.add(pbd);
			}
			postbarDcMapper.insertBatch(fdc);
		}
		postbarMapper.updateByPrimaryKeySelective(postbar);
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}
	@Override
	public Map<String, Object> getHotPostbar(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, postbarMapper.selecHotPostbar(count));
	}

	@Override
	public Map<String, Object> getPostbarById(BaseCo co, String userId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", postbarMapper.getPostbarById(co,userId));
		map.put("Pagination", new Pagination(co, postbarMapper.selectCountOfPostbarById(userId)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> updatePostbar(String postbarId,String userId) {
		//1、校验是否有权限
		Postbar pb = postbarMapper.selectByUserId(postbarId,userId);
		if(pb != null){
			postbarMapper.updatePostbar(postbarId);
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}else{
			return JSONUtil.getJSON(ErrorType.AUTHORITY_ERROR);
		}
	}

	@Override
	public Map<String, Object> getRelevant(String pbId, int count) {
		  Postbar postBar = postbarMapper.selectByPrimaryKey(pbId);
		  List<PostbarDc> list = postbarDcMapper.selectByPostBarId(postBar.getPostbarId());
		  String dcId = "";
		  for (PostbarDc postbarDc : list) {
			  dcId+=postbarDc.getDcId()+",";
		}
		  dcId = dcId.substring(0,dcId.length()-1);
		return JSONUtil.getJSON(ErrorType.SUCCESS,postbarMapper.getRelevant(dcId,count));
	}

	@Override
	public Map<String, Object> getPostbarList(int scId,int hierId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CategoryListOfInternal> category = postbarMapper.selectPostbarListOfInternalCategory(scId);
		List<CategoryListOfHier> hier = postbarMapper.selectPostbarListOfHier(hierId);
		List<Map<String, Object>>  sum= postbarMapper.selectSum();
		
		map.put("category", category);
		map.put("hier", hier);
		map.put("sum", sum);
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> getPostbarOfIndex(int count) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("list", postbarMapper.selectPostbarOfIndex(count));
		map.put("sum", postbarMapper.selectSum());
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> getPostbarRank(int count) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,postbarMapper.selectPostbarRank(count));
	}

	@Override
	public Map<String, Object> getReplyByUserId(BaseCo co, String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", postbarMapper.selectListReplyByUserId(co,userId));
		map.put("Pagination", new Pagination(co, postbarMapper.selectCountReplyByUserId(userId)));
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> getListByKeyWord(BaseCo co, Boolean replyCount,
			Boolean time, String keyWord) {
		Map<String, Object> map = new HashMap<String, Object>();
		//查找出输入的关键词的id
		List<Label>  labList = labelMapper.selectByName(keyWord);
		String labels = "";
		if(labList.size() >0){
			for (Label label : labList) {
				labels +=label.getLabelId()+",";
			}
			labels= labels.substring(0,labels.length()-1);
		}
		map.put("list", postbarMapper.selectListByKeyWord(co,labels,replyCount,time));
		map.put("Pagination", new Pagination(co, postbarMapper.selectCountByKeyWord(labels,replyCount,time)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}
}
